import 'package:fbutton/fbutton.dart';
import 'package:flutter/material.dart';
import 'package:flutter_chip/view/home/wifi/data_utils.dart';
import 'package:fradio/fradio.dart';
import 'package:fsuper/fsuper.dart';

class CalculatorPage extends StatefulWidget {
  @override
  _CalculatorPageState createState() => _CalculatorPageState();
}

class _CalculatorPageState extends State<CalculatorPage> {
  String _showTxt = "";
  String _type = "10";
  String _oldType = "10";

  String value1 = "";
  String value2 = "";
  String operator = "";
  bool isResult = false;

  List _keyList = [
    {
      "key": "A",
      "enable": false,
    },
    {
      "key": "/",
      "enable": true,
    },
    {
      "key": "%",
      "enable": true,
    },
    {
      "key": "清除",
      "enable": true,
    },
    {
      "key": "+",
      "enable": true,
    },
    {
      "key": "B",
      "enable": false,
    },
    {
      "key": "7",
      "enable": true,
    },
    {
      "key": "8",
      "enable": true,
    },
    {
      "key": "9",
      "enable": true,
    },
    {
      "key": "-",
      "enable": true,
    },
    {
      "key": "C",
      "enable": false,
    },
    {
      "key": "4",
      "enable": true,
    },
    {
      "key": "5",
      "enable": true,
    },
    {
      "key": "6",
      "enable": true,
    },
    {
      "key": "x",
      "enable": true,
    },
    {
      "key": "D",
      "enable": false,
    },
    {
      "key": "1",
      "enable": true,
    },
    {
      "key": "2",
      "enable": true,
    },
    {
      "key": "3",
      "enable": true,
    },
    {
      "key": "÷",
      "enable": true,
    },
    {
      "key": "E",
      "enable": false,
    },
    {
      "key": "F",
      "enable": false,
    },
    {
      "key": "0",
      "enable": true,
    },
    {
      "key": ".",
      "enable": true,
    },
    {
      "key": "=",
      "enable": true,
    },
  ];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.black,
      appBar: AppBar(
        backgroundColor: Colors.transparent,
        title: Text(
          "进制计算器",
          style: TextStyle(
            fontSize: 18,
            color: Colors.white,
          ),
        ),
        iconTheme: IconThemeData(color: Colors.white),
        centerTitle: true,
      ),
      body: Column(
        children: <Widget>[
          Expanded(child: _showWidget(), flex: 1),
          _typeWidget(),
          SizedBox(height: 10),
          Container(
              height: 360, width: double.infinity, child: _keyboardWidget())
        ],
      ),
    );
  }

  ///顶部输入显示框
  Widget _showWidget() {
    return Container(
      width: double.infinity,
      alignment: Alignment.bottomRight,
      padding: EdgeInsets.all(10),
      child: Text(
        _showTxt,
        textAlign: TextAlign.end,
        style: TextStyle(
            fontSize: 40, color: Colors.white, fontWeight: FontWeight.w500),
      ),
    );
  }

  ///进制选择
  Widget _typeWidget() {
    Color _normalColor = Color(0XFF9A9999);
    Color _selectlColor = Color(0XFFD8952F);
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceAround,
      children: <Widget>[
        FRadio(
          value: "2",
          width: 60,
          height: 30,
          hasSpace: false,
          border: 2,
          groupValue: _type,
          corner: FRadioCorner.all(15),
          child: FSuper(
            text: '二进制',
            textColor: _normalColor,
            textSize: 12,
          ),
          selectedChild: FSuper(
            text: '二进制',
            textColor: Colors.white,
            textSize: 12,
          ),
          normalColor: _normalColor,
          selectedColor: _selectlColor,
          onChanged: _typeChange,
        ),
        FRadio(
          value: "8",
          width: 60,
          height: 30,
          hasSpace: false,
          border: 2,
          groupValue: _type,
          corner: FRadioCorner.all(15),
          child: FSuper(
            text: '八进制',
            textColor: _normalColor,
            textSize: 12,
          ),
          selectedChild: FSuper(
            text: '八进制',
            textColor: Colors.white,
            textSize: 12,
          ),
          normalColor: _normalColor,
          selectedColor: _selectlColor,
          onChanged: _typeChange,
        ),
        FRadio(
          value: "10",
          width: 60,
          height: 30,
          hasSpace: false,
          border: 2,
          groupValue: _type,
          corner: FRadioCorner.all(15),
          child: FSuper(
            text: '十进制',
            textColor: _normalColor,
            textSize: 12,
          ),
          selectedChild: FSuper(
            text: '十进制',
            textColor: Colors.white,
            textSize: 12,
          ),
          normalColor: _normalColor,
          selectedColor: _selectlColor,
          onChanged: _typeChange,
        ),
        FRadio(
          value: "16",
          width: 60,
          height: 30,
          hasSpace: false,
          border: 2,
          groupValue: _type,
          corner: FRadioCorner.all(15),
          child: FSuper(
            text: '十六进制',
            textColor: _normalColor,
            textSize: 12,
          ),
          selectedChild: FSuper(
            text: '十六进制',
            textColor: Colors.white,
            textSize: 12,
          ),
          normalColor: _normalColor,
          selectedColor: _selectlColor,
          onChanged: _typeChange,
        ),
      ],
    );
  }

  ///底部按钮
  Widget _keyboardWidget() {
    return GridView.count(
      crossAxisCount: 5,
      childAspectRatio: 1,
      crossAxisSpacing: 4,
      mainAxisSpacing: 4,
      children: _keyList
          .map(
            (item) => Builder(
              builder: (context) {
                return Container(
                  alignment: Alignment.center,
                  child: FButton(
                    width: 60,
                    height: 60,
                    shadowColor: Colors.black26,
                    shadowBlur: 10,
                    padding: EdgeInsets.all(0),
                    corner: FButtonCorner.all(30),
                    text: item['key'],
                    disabledTextColor: Colors.grey,
                    clickEffect: true,
                    textColor: Colors.white,
                    color: _getBackColor(item['key'], item['enable']),
                    onPressed: () =>
                        !item['enable'] ? null : _keyOnClick(item['key']),
                  ),
                );
              },
            ),
          )
          .toList(),
    );
  }

  Color _getBackColor(String value, bool isEnable) {
    if ("1,2,3,4,5,6,7,8,9,0,.,A,B,C,D,E,F".contains(value)) {
      return isEnable ? Color(0XFF2B2B2B) : Color(0XFF9A9999);
    } else {
      return isEnable ? Color(0XFFD8952F) : Color(0XFF9A9999);
    }
  }

  ///按钮监听
  void _keyOnClick(String value) {
    print("按下：$value  isResult=$isResult");
    if (isResult) {
      _showTxt = "";
      operator = "";
      value1 = "";
      value2 = "";
      isResult = false;
    }
    if ("1,2,3,4,5,6,7,8,9,0,.,A,B,C,D,E,F".contains(value)) {
      _showTxt += value;
      if (operator.isEmpty) {
        value1 += value;
      } else {
        value2 += value;
      }
    } else if ("+,-,x,÷,%,/".contains(value)) {
      if (value == "-" && value1 == "-") {
        return;
      }
      if (value1.isEmpty && "+,x,÷,%,/".contains(value)) {
        return;
      }
      if ("+,x,÷,%,/".contains(value) && value1 == "-") {
        return;
      }
      if (value == "-" && value1.isEmpty) {
        value1 += value;
      } else {
        operator = value;
      }
      _showTxt += value;
    } else if ("清除" == value) {
      _showTxt = "";
      operator = "";
      value1 = "";
      value2 = "";
      _oldType = _type;
    } else if (value == "=") {
      calculator();
    }
    setState(() {});
  }

  ///进制切换
  void _typeChange(String value) {
    _type = value;
    switch (value) {
      case "2":
        _keyList.forEach((item) {
          if ("0,1,+,-,=,清除".contains(item['key'])) {
            item['enable'] = true;
          } else {
            item['enable'] = false;
          }
        });
        break;
      case "8":
        _keyList.forEach((item) {
          if ("0,1,2,3,4,5,6,7,+,-,=,清除".contains(item['key'])) {
            item['enable'] = true;
          } else {
            item['enable'] = false;
          }
        });
        break;
      case "16":
        _keyList.forEach((item) {
          if (".,x,÷".contains(item['key'])) {
            item['enable'] = false;
          } else {
            item['enable'] = true;
          }
        });
        break;
      default:
        _keyList.forEach((item) {
          if ("A,B,C,D,E,F".contains(item['key'])) {
            item['enable'] = false;
          } else {
            item['enable'] = true;
          }
        });
        break;
    }
    setState(() {});
    if (value1.isEmpty) {
      _oldType = value;
      return;
    }
    print("value1=$value1  value2=$value2");
    if (_oldType == "10") {
      value1 =
          int.tryParse(value1).toRadixString(int.parse(_type)).toUpperCase();
      _showTxt = value1;
      if (value2.isNotEmpty) {
        value2 =
            int.tryParse(value2).toRadixString(int.parse(_type)).toUpperCase();
        _showTxt += operator + value2;
      }
    } else if (_oldType == "2") {
      String old1 = value1;
      value1 = DataUtils.binToInt(old1)
          .toRadixString(int.parse(_type))
          .toUpperCase();
      _showTxt = value1;
      if (value2.isNotEmpty) {
        String old2 = value2;
        value2 = DataUtils.binToInt(old2)
            .toRadixString(int.parse(_type))
            .toUpperCase();
        _showTxt += operator + value2;
      }
    } else if (_oldType == "8") {
      String old1 = value1;
      value1 = DataUtils.octalToInt(old1)
          .toRadixString(int.parse(_type))
          .toUpperCase();
      _showTxt = value1;
      if (value2.isNotEmpty) {
        String old2 = value2;
        value2 = DataUtils.octalToInt(old2)
            .toRadixString(int.parse(_type))
            .toUpperCase();
        _showTxt += operator + value2;
      }
    } else if (_oldType == "16") {
      String old1 = value1;
      value1 = DataUtils.hexToInt(old1)
          .toRadixString(int.parse(_type))
          .toUpperCase();
      _showTxt = value1;
      if (value2.isNotEmpty) {
        String old2 = value2;
        value2 = DataUtils.hexToInt(old2)
            .toRadixString(int.parse(_type))
            .toUpperCase();
        _showTxt += operator + value2;
      }
    }
    setState(() {});
    isResult = false;
    _oldType = value;
  }

  ///计算
  void calculator() {
    print("原始计算值：$value1 | $operator | $value2");
    var first, second, result;
    if (_type == "16") {
      first = DataUtils.hexToInt(value1);
      second = DataUtils.hexToInt(value2.isEmpty ? "0" : value2);
    } else if (_type == "2") {
      first = DataUtils.binToInt(value1);
      second = DataUtils.binToInt(value2.isEmpty ? "0" : value2);
    } else if (_type == "8") {
      first = DataUtils.octalToInt(value1);
      second = DataUtils.octalToInt(value2.isEmpty ? "0" : value2);
    } else {
      if (value1.contains(".") || value2.contains(".")) {
        first = double.parse(value1);
        second = double.tryParse(value2.isEmpty ? '0' : value2);
      } else {
        first = int.parse(value1);
        second = int.tryParse(value2.isEmpty ? '0' : value2);
      }
    }
    print("格式化：$first  $second");
    switch (operator) {
      case "+":
        result = first + second;
        break;
      case "-":
        result = first - second;
        break;
      case "x":
        result = first * second;
        break;
      case "/":
        result = (first / second).toInt();
        break;
      case "÷":
        result = first / second;
        break;
      case "%":
        result = (first - (first / second).toInt() * second).toInt();
        break;
      default:
        result = first;
        break;
    }
    if (_type != "10") {
      _showTxt +=
          "\n${result.toInt().toRadixString(int.parse(_type)).toUpperCase()}";
    } else {
      _showTxt += "\n$result";
    }
    print("计算值：$value1 $operator $value2 = $result");
    isResult = true;
    setState(() {});
  }
}
